import ReactDOM from 'react-dom';
import React from 'react';
import { toJS } from 'mobx';
import base from './base';
import * as VariableKeys from '../constants/variableKey';
import * as API_REQ from '../apis/form';
import { Tools,Toast,Bubble } from 'weaver-mobile';
import { _, DetailUtil, FieldUtil, GlobalUtil,WfForm_Public ,wfWaterMark, InvoiceUtil} from './pcPublic';
import { buildUrlStr } from './forwardPage';
import * as Common from './common';
import * as continuationProcessUtil from './continuationProcessUtil';
const jQuery = window.jQuery;
const getLabel = Common.getLabel;

//表单操作完成后返回到源页面
export const returnSourcePage = (params = {}) => {
    GlobalUtil.verifyCustomRegisterEvent(WfForm_Public.OPER_CLOSE, ()=>{

        const { wfGlobalStore } = base;
        const { urlParams,commonParam } = wfGlobalStore;
        const { iscreate, msgSubmitFormAction } = commonParam;

        params.iscreate = iscreate;
        const openCustomUrl = (customReturnUrl)=>{
            Toast.hide();
			
			let closeFunc = () => {
				if(judgeSupportOpenSDK() && !customReturnUrl){
					window.em.ready(function(){
						window.em.closeWindow();
						window.em.postBroadcast({
							name: "_closeWfFormCallBack",
							text: JSON.stringify(params)
						});
					})
				}else{
					let returnUrl = "/spa/workflow/static4mobile/index.html#/center/doing";
					if(!!customReturnUrl){
						returnUrl = customReturnUrl;
					}else{
						if(!!Tools.ss.getStr("__wf__openform__returnurl__"))
							returnUrl = Tools.ss.getStr("__wf__openform__returnurl__");
						returnUrl = returnUrl.replace(/(\?_random=\d+)#/, "#");
						if(returnUrl.indexOf("retainCondition") === -1)
							returnUrl = `${returnUrl}${returnUrl.indexOf("?") > -1 ? "&" : "?"}retainCondition=1`;
					}
					returnUrl = returnUrl.replace(/(.html|.jsp)\?/, `$1?_random=${new Date().getTime()}&`);
					returnUrl = returnUrl.replace(/(.html|.jsp)#/, `$1?_random=${new Date().getTime()}#`);
					forwardPage(returnUrl);
				}
			}

            if(urlParams.isOpenContinuationProcess && (params.source == 'submit' || params.source == 'forceOver' || params.source == 'forwardSubmit' || params.source == 'delete')) {
                try{
                    //连续处理调用时切换下一条流程
                    continuationProcessUtil.switchRequest('next', closeFunc, true);
                    return;
                }catch(e){console && console.log(e)}
            }
			
			closeFunc();
        }
		
        if (msgSubmitFormAction){//从消息中心打开的关闭当前webview
            if( msgSubmitFormAction == '1'&&  window.em && window.em.checkJsApi("closeWindow")){
                window.em.closeWindow()
            } else {
                openCustomUrl(msgSubmitFormAction);
            }
        }else{
            const customReturnUrl = Tools.ss.getStr("__wf__openform__custom__returnurl__");   //打开表单链接指定返回地址
            openCustomUrl(customReturnUrl);
        }
    }, params);
}
window.returnSourcePage = returnSourcePage;

//表单自身调用，重新加载表单，适用了保存等情况跳转，需经过中转页面刷全局对象
export const reloadFormPage = (params) =>{
    const url = `/spa/workflow/forwardMobileForm.html?${buildUrlStr(params)}`;
    forwardPage(url);
}

//跳转自定义页面地址
export const goToCustomPage = (params={}) =>{
    const {wfGlobalStore} = base;
    let {requestid,pcUrl='',mobileUrl=''}  = params;
    const {hasFreeNode = false} = params;
    const urlParam = {
        requestid:params.requestid,
        workflowid:params.workflowid,
        isbill:params.isbill,
        formid:params.formid,
        nodeid:params.nodeid,
        isfromtab:params.isfromtab,
        f_weaver_belongto_userid:params.f_weaver_belongto_userid,
        f_weaver_belongto_usertype:params.f_weaver_belongto_usertype,
        showE9Pic: "1",
        isFromWfForm:true,
        authSignatureStr:params.authSignatureStr,
        authStr:params.authStr,
        isFree:params.isFree,
        isAllowNodeFreeFlow:params.isAllowNodeFreeFlow,
        isReadOnlyModel:'true',
        hasFreeNode:hasFreeNode ? "1" :"0",
        isMobile:'1',
        isFromAutodirect:true
    };
    const {rightMenu = {}} = base.wfOperateStore;
    const {isFree = '0',isAllowNodeFreeFlow = '0'} = rightMenu;
    urlParam['isFree'] = isFree;
    urlParam['isAllowNodeFreeFlow'] = isAllowNodeFreeFlow;

    let url = '';
    if (pcUrl != '') {
        pcUrl += pcUrl.indexOf("?") > 0 ? "&" : "?";
        pcUrl += "requestid="+requestid+"&workflowid="+params.workflowid;
        url = pcUrl;
        if (mobileUrl !== '') {
            mobileUrl += mobileUrl.indexOf("?") > 0 ? "&" : "?";
            mobileUrl += "requestid="+requestid+"&workflowid="+params.workflowid;
            url = mobileUrl;
        }
    } else {
        url = `/workflow/workflowDesign/m-readOnly.html?v=20200312&isFromWfForm=true&${buildUrlStr(urlParam)}`;
    }
    forwardPage(url);
}
//跳转页面(location跳转前先触发unmount事件)
export const forwardPage = (url) =>{
    ReactDOM.unmountComponentAtNode(document.getElementById('root'));
    window.location.replace(url)
}

//判断是否是EM终端,支持弹webview的SDK
export const judgeSupportOpenSDK = () =>{
    const isEmobile = Tools.mobileDetect().isEmobile();
    if(isEmobile && window.em)
        return window.em.checkJsApi("openLink") && window.em.checkJsApi("closeWindow");
    return false;
}

//页面标题
export const getPageTitle = () => {
    let pageTitle = "";
    const { wfGlobalStore, wfLayoutStore } = base;
    const { commonParam } = wfGlobalStore;
    const { mainData } = wfLayoutStore;
    const { iscreate, workflowname } = commonParam;
    if (!_.isEmpty(commonParam) && parseInt(iscreate) === 1) {
        pageTitle = `${getLabel(83443, '创建')} - ${workflowname}`;
    } else if (mainData.has("field-1")) {
        pageTitle = mainData.get("field-1").value;
    } else {
        pageTitle = `${getLabel(553, '处理')} - ${workflowname}`;
    }
    return pageTitle;
}

//修改meta控制缩放
export const controlViewPort = (pathname='/req',showContent) => {
    const { urlParams,commonParam } = base.wfGlobalStore;
    const { wfSignInputStore } = base.allStores;
    const { variableMap } = wfSignInputStore;
    let showSignArea = variableMap.has("showSignArea") ? toJS(variableMap.get("showSignArea")) : false;
    if(showContent == true || showContent == false) showSignArea = showContent;
    const isReadPCLayout = urlParams.layoutAnalysisType == "2" || commonParam.layoutAnalysisType == "2";
    const viewport = document.querySelector("meta[name=viewport]");
    if(viewport != null){
        if(isReadPCLayout && pathname === "/req" && !showSignArea){
            const screenWidth = window.screen.width;
            const contentWidth = jQuery(".excelMainTable") ? jQuery(".excelMainTable").width() : document.body.scrollWidth;
            const defScale = screenWidth/(contentWidth+50);
            viewport.setAttribute("content", "width=device-width, initial-scale="+defScale+", maximum-scale=5.0, minimum-scale=0.1");
        }else
            viewport.setAttribute("content", "width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0");
    }
}

//打印耗时
export const printDuration = (params) => {
    try {
        if (window.console) {
            console.log(`请求id: ${params.requestid}`);
            console.log(`js加载耗时: ${window.JS_LOAD_DURATION || 0}毫秒`);
            console.log(`服务端耗时: ${window.SERVER_DURATION || 0}毫秒`);
            console.log(`接口耗时: ${window.API_DURATION || 0}毫秒`);
            console.log(`渲染耗时: ${window.DISPATCH_DURATION || 0}毫秒`);
            console.log(`总耗时: ${window.REQ_LOAD_DURATION / 1000 || 0}秒`);
        }
    } catch (e) { }
}

//重新加载表单
export const reloadRequestPage = (params, appendUserStr = true) => {
    const { wfGlobalStore } = base;
    wfGlobalStore.setCloseNeedPrompt(false);
    if (appendUserStr === true) {     //扩展用户信息
        const { f_weaver_belongto_userid, f_weaver_belongto_usertype } = wfGlobalStore.commonParam;
        params = { ...{ f_weaver_belongto_userid, f_weaver_belongto_usertype }, ...params };
    }
    //添加连续处理信息
    const { isOpenContinuationProcess } = wfGlobalStore.urlParams;
    params = {...params, isOpenContinuationProcess}

    if(params.requestid == wfGlobalStore.commonParam.requestid) {
        params.isRefresh = '1';
        appendContinuationParams(params);
    }

    reloadFormPage(params);
}

//拼接连续处理参数
export const appendContinuationParams = (urlParam = {}) => {
    const {wfGlobalStore} = base;
    const { continuationProcessInfo } = wfGlobalStore;
    if(continuationProcessInfo.loaded) {
        urlParam.currentIndex = continuationProcessInfo.currentIndex;
        urlParam.counts = continuationProcessInfo.counts;
    }
    return urlParam;
}

//空值转换
export const convertNull = (value, bool = true) => {
    if (value === null || typeof value === "undefined")
        return "";
    else
        return bool ? value.toString() : value;
}

//加载代码块及custompage
export const loadScript = () => {
    const promiseList = GlobalUtil.generateScriptPromiseList();
    const { isSourceLayout, commonParam={} } = base.wfGlobalStore;
    const{ useInvoiceCloud } = commonParam;
    const { layoutSourceInfo } = base.wfLayoutStore;
    Promise.all(promiseList).then((result)=>{
        jQuery("#customScriptDiv").html("");
        if(isSourceLayout)  //源码模板代码块不发请求
            result.push(layoutSourceInfo.script);
        result.forEach((item,index) =>{
            try{
                jQuery("#customScriptDiv").append(`<div class="_custom_script_${index}">${GlobalUtil.manageScriptContent(item)}</div>`);
            }catch(e){}
        });
        GlobalUtil.loadCustomFiles("js"); 
        GlobalUtil.loadFormulaResource();
        //公文流程执行页面加载事件
        const { odocInfo } = base.wfLayoutStore;
        if(odocInfo && odocInfo.docFlag === true && window.oDocUtil.loadOdocConfig)
            window.oDocUtil.loadOdocConfig();
    });
    if(useInvoiceCloud === true){
        InvoiceUtil.bindOnMessage()
    }
}

//添加明细行
export const addRow = (symbol, openEdit = true) => {
    const addRowIndex = DetailUtil.addRow(symbol);
    if(openEdit && (!!addRowIndex || addRowIndex === 0))
        editRow(symbol, addRowIndex);
    return addRowIndex;
}

//删除明细行
export const delRow = (detailMark) => {
    const detailObj = DetailUtil.getDetailObj(detailMark);
    if (detailObj === null)
        return;
    const rowArr = DetailUtil.getDetailCheckedRowArr(detailObj);
    if (rowArr.length === 0)
        return;
    Common.showConfirm({
        title: getLabel(15097, '确定要删除吗？'),
        okEvent: () => {
            DetailUtil.delAssignRow(detailMark, rowArr);
        }
    });
}

//编辑明细行
export const editRow = (symbol, rowIndex) => {
    const detailObj = DetailUtil.getDetailObj(symbol);
    if (detailObj === null)
        return;
    const isCardEdit = DetailUtil.judgeIsCardEdit(detailObj);
    if (!isCardEdit)
        return;
    GlobalUtil.verifyCustomRegisterEvent(WfForm_Public.OPER_EDITDETAILROW, ()=>{
        window.historyRoute.push({
            pathname:"/req/editDetailRow",
            state: {detailMark:symbol, rowIndex:rowIndex}
        });
    }, {symbol, rowIndex});
}

/**
 * 控制提示组件
 * @param {*} mark  提示字段则为field110_3、提示明细表则是detail_2
 * @param {*} promptType   1提示必填字段，2提示行规则赋值字段不可编辑，3提示未新增明细
 */
export const showPrompt = (mark, promptType) => {
    if (!mark)
        return;
    const { wfLayoutStore } = base;
    const { fieldAttrMap, cellInfo } = wfLayoutStore;
    let tableMark = "";
    let fieldid = "";
    let fieldAttr = null;
    let rowIndex = -1;
    let lableText = "";
    if (promptType === 1 || promptType === 2) {
        if (mark.indexOf("_") > -1) {
            fieldid = mark.substring(5, mark.indexOf("_"));
            rowIndex = parseInt(mark.substring(mark.indexOf("_") + 1));
        } else {
            fieldid = mark.substring(5)
        }
        fieldAttr = fieldAttrMap.get(fieldid);
        tableMark = fieldAttr.tableMark;
        lableText = fieldAttr.fieldlabel;
    } else if (promptType === 3) {
        lableText = `${getLabel(19325, '明细表')}${mark.substring(7)}`;
    }
    let changeTabMark = "";
    if (promptType === 1) {
        //如果字段是标签页字段，需默认选择标签页
        const belSymbol = _.get(cellInfo, ["fieldCellInfo", fieldid, "symbol"]) || "";
        if (belSymbol.indexOf("mc_") > -1 || belSymbol.indexOf("detail_") > -1)   //多字段、明细字段再取上一层
            changeTabMark = _.get(cellInfo, ["subPanelInfo", belSymbol, "symbol"]) || "";
        else
            changeTabMark = belSymbol;
    } else if (promptType === 3) {
        changeTabMark = _.get(cellInfo, ["subPanelInfo", mark, "symbol"]) || "";
    }
    //提示区域在标签页中，需要切换标签页到选中状态
    if (changeTabMark.indexOf("tab_") > -1) {
        const tabPanelInfo = _.get(cellInfo, ["subPanelInfo", changeTabMark]) || {};
        if (!_.isEmpty(tabPanelInfo)) {
            let changeInfo = {};
            changeInfo[`tabarea_${tabPanelInfo.rowid}_${tabPanelInfo.colid}_showid`] = changeTabMark;
            wfLayoutStore.batchControlVariableMap(changeInfo);
        }
    }
    //明细字段提示必填，需跳转路由
    if (promptType === 1 && tableMark.indexOf("detail_") > -1) {
        editRow(tableMark, rowIndex);
    }
    const showBubble = () => {
        const isFieldOnlyShow = fieldAttr && fieldAttr.isonlyshow === 1;
        let noticeInfo = "";
        let locateObj;
        if (promptType === 1 || promptType === 2)
            locateObj = jQuery("[data-fieldmark='" + mark + "']");
        else if (promptType === 3)
            locateObj = jQuery("table#oTable" + (parseInt(mark.substring(7)) - 1));
        const existLocateObj = locateObj.size() > 0;
        if (existLocateObj && locateObj.is(":visible") && !isFieldOnlyShow) {     //定位元素可见
            if (promptType === 1)
                noticeInfo = getLabel(21423, "未填写");
            else if (promptType === 2)
                noticeInfo = getLabel(386152, "为行规则赋值字段，修改无效");
            else if (promptType === 3)
                noticeInfo = getLabel(383709, "未新增数据");
            //滚动定位
            if (tableMark.indexOf("detail_") === -1) {
                const overflowObj = jQuery(".wf-req-content");
                const totalOffsetTop = locateObj.offset().top + overflowObj.scrollTop();
                const promptOffsetTop = locateObj.offset().top + locateObj.height() + 38;
                //控制竖向滚动条，将定位DOM放置在可视区域
                if (promptOffsetTop <= (overflowObj.offset().top + 10) || promptOffsetTop >= jQuery(window).height()) {
                    const setOffsetTop = (jQuery(window).height() - locateObj.height() - overflowObj.offset().top) / 2;      //设置字段区域底部距离浏览器顶部偏移一半
                    overflowObj.scrollTop(totalOffsetTop - setOffsetTop);      //滚动至可视区域
                }
            }
        } else {
            if (promptType === 1) {
                noticeInfo = isFieldOnlyShow ? getLabel(507230,"未获取到值,请检查表单填写情况！") : getLabel(386149, "字段未填值,字段内容被隐藏！");
            } else if (promptType === 3) {
                if (!existLocateObj)
                    noticeInfo = getLabel(386150, "未新增数据,明细表未放在模板上！");
                else
                    noticeInfo = getLabel(386151, "未新增数据,明细区域被隐藏！");
            }
        }
        Bubble.warning(React.createElement('span',{dangerouslySetInnerHTML:{__html:`"${lableText}"${noticeInfo}`}}), 2);
    }
    showBubble();
}

//调用客户自定义回掉函数
export const doDefinitionCallBackFun = (fieldid, rowIndex, ids, datas, fieldAttr) => {

}

//流程导入
export const doReqImport = (imprequestid) =>{
    const {commonParam} = base.wfGlobalStore;
    const {workflowid,formid,isbill,nodeid,nodetype,isagent,beagenter} = commonParam;
    let requestname = '';
    let requestlevel = '';
    const fieldObj = FieldUtil.getFieldValObj(-1,-1);
    const fieldObjReqLevel = FieldUtil.getFieldValObj(-2,-1);
    if(fieldObj) {
        const {valueObj = {}} = fieldObj;
        const {value = ''} = valueObj;
        requestname = value;
    }
    if(fieldObjReqLevel) {
        const {valueObj = {}} = fieldObjReqLevel;
        const {value = ''} = valueObj;
        requestlevel = value;
    }
    const importParams = {
        src:"import",
        imprequestid:imprequestid,
        workflowid:workflowid,
        formid:formid,
        isbill:isbill,
        nodeid:nodeid,
        "nodetype":nodetype,
        isagent:isagent,
        beagenter:beagenter,
        requestname:requestname,
        requestlevel:requestlevel
    };
    API_REQ.requestImport(importParams).then(data=>{
        reloadRequestPage({requestid:data.requestid});
    });
}

//获取流程干预默认值
export const getIntervenorDefaultV = (data = {}) => {
    let updateinfo = {};
    let { items = [] } = data;
    let nodeOperators = data.replacedatas || [];
    if (items.length > 0) {
        items.map((item) => {
            const { labelcol, fieldcol, label, conditionType, domkey = [], browserConditionParam = {}, options = [] } = item;
            if (conditionType == 'SELECT') {
                options.map((o) => {
                    if (o.selected) updateinfo[domkey[0]] = o.key;
                })
            } else if (conditionType == 'BROWSER') {
                const { replaceDatas = [] } = browserConditionParam;
                let ids = [];
                replaceDatas.map((o) => {
                    ids.push(o.id);
                })
                updateinfo[domkey[0]] = ids.join(',');
                if ('Intervenorid' == domkey[0]) nodeOperators = replaceDatas;
            }
        });
    }
    if (nodeOperators && nodeOperators.length > 0) {
        let ids = [];
        let operatortypes = [];
        nodeOperators.map(o => {
            const { id, IntervenoridType = '' } = o;
            ids.push(id);
            operatortypes.push(IntervenoridType);
        });
        updateinfo.Intervenorid = ids.join(',');
        updateinfo.IntervenoridType = operatortypes.join(',');
    }
    return updateinfo;
}

//滚动dom元素到页面可视区域
export const scrollDom = (dom=".wf-req-freeWorkflowSimple", borderHeightLight=false,msg) =>{
    let  remarktop = parseInt(jQuery(dom).offset().top);
    let scrolltop = 0;
    //判断dom元素区域是否在可视区域
    const isVisual = remarktop > 0 && (remarktop - jQuery('.wf-req-top').height() + 200 <  jQuery('.wf-req-content').height());
    if(!isVisual) {
        if(remarktop - jQuery('.wf-req-top').height() + 200 > jQuery('.wf-req-content').height()){
            scrolltop = remarktop + jQuery('.wf-req-content').scrollTop() - 250;
        }
        if(remarktop <  (jQuery('.wf-req-top').height())){
            if(remarktop < 0) remarktop = remarktop * -1;
            scrolltop = jQuery('.wf-req-content').scrollTop() - remarktop - jQuery('.wf-req-top').height()-150;// -100;
        }
        jQuery('.wf-req-content').animate({ scrollTop: scrolltop + "px" }, 0);
    }

    if(msg){
        Bubble.warning(msg,2);
        const { controlVariableMap } = base.allStores.wfSignInputStore;
        controlVariableMap(VariableKeys.CURR_OPERATE_TYPE,{});
    }
    if(borderHeightLight){
        //闪动2下
        let time=0;
        let flag=true;
        for(var i=0;i<4;i++)
        {
            time+=500;
            setTimeout(function(){
                 flag = !flag;
                 if(flag){
                    controlColor(dom, "#FFFFFF")
                 }else{
                    controlColor(dom, "#DFF1FF")
                 }
            },time);    
        }
    }
}
const controlColor=(dom, color)=>{
    jQuery(dom+' div').each(function(){
        if(!(jQuery(this).hasClass("am-select-ghost")||jQuery(this).hasClass("am-select-primary"))){
            jQuery(this).css("background",color);
        }
    })

}
window.scrollDom = scrollDom;

//切换tab是触发的事件
export const tabChangTriggerEvent=(tab="",nowTabKey)=>{
    const {odocInfo={}}=base.wfLayoutStore;
    const {setTabKey,tabKey}=base.wfGlobalStore;
    const {mobileInfo={}, imagefileId}=odocInfo;
    const {isDownload}=mobileInfo;
    if(nowTabKey!="odoc" && tab=="odoc" && isDownload){
        setTimeout(() => {
            setTabKey("layout")
        }, 3000);
        window.WfForm.downLoadFile(imagefileId, "/req");
    }else if(nowTabKey!="odoc" && tab=="odoc" ){
        const {variableMap,controlVariableMap,commonParam}=base.wfGlobalStore;
        const {mobileInfo={}}=odocInfo;
        const {addressUrl=""}=mobileInfo;
        const odocSrc = variableMap.has(`wf-odocSrc`) ? variableMap.get(`wf-odocSrc`) : "";
        if(!odocSrc){
            const {authSignatureStr, authStr,requestid} = commonParam;
            let newAddressUrl = `${addressUrl}?authSignatureStr=${authSignatureStr}&authStr=${authStr}&requestid=${requestid}`
            controlVariableMap("wf-odocSrc",newAddressUrl);
        }
    }else if (tab.indexOf('custom_') > -1) {
        try {
            let fun = window.WfForm.customTabFunObj[tab];
            if (typeof fun === 'function') {
                fun();
            }
        } catch (e) {
            if (window.console) console.log(e);
        }
    }
    //后执行注册事件
    window.WfForm.triggerAction(window.WfForm.ACTION_SWITCHTAB, [tab, nowTabKey]);
}

/**
 * 加载水印
 */
export const loadWaterMark = () => {
    const {waterMarkInfo} = base.wfGlobalStore.commonParam;
    if(waterMarkInfo) {
        const {contentType = 0,content = "",width = 0,height = 0,transparency = 0,rotationAngle = 0,mobileisopen = false} = waterMarkInfo;
        if(!mobileisopen) return;
        const waterMarkOptions = {
            fontStyle: "font-size:18px;color:#000;",
            rotate: 360-rotationAngle,
            alpha: transparency/100,
            width,
            height
        };

        if(contentType == 1) {
            let tempContent  = content;
            const regx = /<span key=\"(.*?)\"><\/span>/g;
            while (regx.exec(content) != null) {
                const fieldMark  = RegExp.$1;
                const valShowName =  GlobalUtil.getWaterMarkFieldShowName(fieldMark);
                tempContent = tempContent.replace(`<span key="${fieldMark}"></span>`,`<span>${valShowName}</span>`);
            }
            waterMarkOptions.text = tempContent;
        }
        if(contentType == 2) waterMarkOptions.src = content;
        wfWaterMark(waterMarkOptions);
    }
}


export const switchTabFun=(tabKey,type)=>{
    const { wfGlobalStore ,wfCommunicateStore,wfSignListStore} = base.allStores;
    const { comSetStoreState } = wfCommunicateStore;
    const nowTabKey = wfGlobalStore.tabKey;
    if(tabKey.indexOf('custom_') === -1){   //非自定义，自定义走绑定事件
        if(type === 1){
            wfGlobalStore.setTabKey(tabKey);
        }
        //流程图、流程状态、相关资源跳路由
        const routeArr = ["picture", "status", "resource"];
        if(_.includes(routeArr, tabKey)){
            window.historyRoute.push(`/req/${tabKey}?${buildUrlStr(wfGlobalStore.urlParams)}`);
        }
    }
    tabChangTriggerEvent(tabKey, nowTabKey);
}